package com.zxl.yjb.app.update;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.zxl.yjb.R;
import com.zxl.yjb.bean.MessageEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadApkFileService extends Service
{
	/*private String savePath = "";
	private int progress;
	private String apkFilePath = "";
	private String tmpFilePath = "";
	private String apkFileSize;
	private String tmpFileSize;
	
	private boolean interceptFlag;*/
	
	private File updateDir = null;
	private File updateFile = null;
	
	
	private static final int DOWNLOAD_COMPLETE = 0;
	private static final int DOWNLOAD_FAIL = 1;
	
	
	private CheckVersion mUpdate;
	private NotificationManager notificationManager;
	private Notification notification;
	private Notification.Builder builder;
	private RemoteViews downloadApkView;
	private int notificationId = 1001;

	private TextView update_apk_file_tv_value;
	private ProgressBar update_apk_file_progress;
	
	
	private Handler mHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			case DOWNLOAD_COMPLETE:
				/*Uri uri = Uri.fromFile(updateFile);
				Intent installIntent = new Intent(Intent.ACTION_VIEW);
                installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
                 
                notification.setLatestEventInfo(DownloadApkFileService.this, "上海地铁", "下载完成,点击安装。", null);
                notificationManager.notify(0, notification);*/
				
				File apkfile = new File(updateFile.getAbsolutePath());
				if (!apkfile.exists())
				{
					return;
				}
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setDataAndType(Uri.parse("file://" + apkfile.toString()),
						"application/vnd.android.package-archive");
				getApplicationContext().startActivity(intent);
				notificationManager.cancelAll();
	                 
                //停止服务
                stopSelf();
				break;
				
			case DOWNLOAD_FAIL:
				Toast.makeText(getApplicationContext(), "更新失败", Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};

	
	
	@Override
	public void onCreate()
	{
		init();
	}

	
	
	private void init()
	{
		notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);

		downloadApkView = new RemoteViews(getPackageName(),
				R.layout.download_apk_file_notification_view);
		builder = new Notification.Builder(this)
				.setAutoCancel(true)
				.setContent(downloadApkView)
				.setSmallIcon(R.mipmap.ic_launcher);


		notification = new Notification();
		/*notification.icon = R.drawable.ic_launcher;
		notification.tickerText = "下载中...";
		notification.defaults = Notification.DEFAULT_LIGHTS;
		downloadApkView = new RemoteViews(getPackageName(),
				R.layout.download_apk_file_notification_view);
		notification.contentView = downloadApkView;*/
		notification = builder.build();
		notificationManager.notify(0, notification);
	}

	
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		// TODO Auto-generated method stub
		if (intent != null)
		{
			mUpdate = (CheckVersion) intent.getSerializableExtra("mUpdate");
		}
		
		//创建文件
	    if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
	    {
	    	String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/shanghuijia/";
	        updateDir = new File(path);
	        updateFile = new File(updateDir, "shanghuijia.apk");
	    }
		
		new Thread(mdownApkRunnable).start();
		
		return super.onStartCommand(intent, flags, startId);
	}

	
	
	/**
	 * 下载apk文件线程
	 */
	private Runnable mdownApkRunnable = new Runnable()
	{
		Message message = mHandler.obtainMessage();
		
		@Override
		public void run()
		{
			Message message = mHandler.obtainMessage();
			message.what = DOWNLOAD_COMPLETE;
			try
			{
				if(!updateDir.exists())
				{
					updateDir.mkdirs();
				}
				if(!updateFile.exists())
				{
					updateFile.createNewFile();
				}
				
				long downloadSize = downloadUpdateFile(mUpdate.getAppUrl(),updateFile);
                if(downloadSize>0)
                {
                    //下载成功
                    mHandler.sendMessage(message);
                }
				
				
			} catch (Exception e)
			{
				// TODO: handle exception
				e.printStackTrace();
				Message errmessage = mHandler.obtainMessage();
				errmessage.what = DOWNLOAD_FAIL;
				mHandler.sendMessage(errmessage);
			}
			
			

		}
	};

	
	
	public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception
	{


        int downloadCount = 0;
        int currentSize = 0;
        long totalSize = 0;
        int updateTotalSize = 0;
         
        HttpURLConnection httpConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
         
        try {
            URL url = new URL(downloadUrl);
            httpConnection = (HttpURLConnection)url.openConnection();
            httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");
            if(currentSize > 0) 
            {
                httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");
            }
            httpConnection.setConnectTimeout(10000);
            httpConnection.setReadTimeout(20000);
			httpConnection.setRequestProperty("Accept-Encoding", "identity");
			updateTotalSize = httpConnection.getContentLength();
            if (httpConnection.getResponseCode() == 404)
            {
                throw new Exception("fail!");
            }
            is = httpConnection.getInputStream();                  
            fos = new FileOutputStream(saveFile, false);
            byte buffer[] = new byte[4096];
            int readsize = 0;
            while((readsize = is.read(buffer)) > 0)
            {
                fos.write(buffer, 0, readsize);
                totalSize += readsize;
                //为了防止频繁的通知导致应用吃紧，百分比增加10才通知一次
                if((downloadCount == 0) || (int) (totalSize*100/updateTotalSize)-5>downloadCount)
                {
					downloadApkView.setProgressBar(R.id.update_apk_file_progress,100,(int)totalSize*100/updateTotalSize,false);
//                    notification.setLatestEventInfo(this, "正在下载", (int)totalSize*100/updateTotalSize+"%", null);
					downloadApkView.setTextViewText(R.id.update_apk_file_tv_value,"正在下载"+(int)totalSize*100/updateTotalSize+"%");
					EventBus.getDefault().post(new MessageEvent("downloadProgress",(int)totalSize*100/updateTotalSize));
                    notificationManager.notify(0, notification);
                    downloadCount += 5;
                }                       
            }
        } 
        finally 
        {
            if(httpConnection != null) 
            {
                httpConnection.disconnect();
            }
            if(is != null) 
            {
                is.close();
            }
            if(fos != null) 
            {
                fos.close();
            }
        }
        return totalSize;
    }
	
	
	
	
	@Override
	public void onDestroy()
	{
		// TODO Auto-generated method stub
		super.onDestroy();
		stopSelf();
	}

	
	
	@Override
	public IBinder onBind(Intent intent)
	{
		// TODO Auto-generated method stub
		return null;
	}


}
